<?php
require 'vendor/autoload.php';

class NewsPersistor {

	private $dbConnection;
	private $returnValue;
	private $rssSourceManager;
	
	function __construct($dbConnector,$rssSourceManager) {
		$this->dbConnection = $dbConnector->connectToDB();
		$this->rssSourceManager = $rssSourceManager;
	}
	
	function saveNews($news) {	
		$hash = $this->generateHash($news->getTitle(),$news->getshortName());
		if ($this->newsAlreadySaved($hash) == 'FALSE'){
			$this->returnValue = $this->save($news,$hash);
		}
		else{
			$this->returnValue = false;
		}
		
		return($this->returnValue);
	}
	
	private function generateHash($title,$sourceShortName){
		$stringToBeHashed = $title . $sourceShortName;
		$hash = hash('md5',$stringToBeHashed);
		return ($hash);	
	}
	
	private function newsAlreadySaved($hash){
		$queryHandler = $this->dbConnection->prepare('SELECT Id FROM news WHERE Id = :id');
		$queryHandler->setFetchMode(PDO::FETCH_OBJ);
		$queryHandler->bindParam(':id', $hash);
		$queryHandler->execute();
		$queryResult = $queryHandler->fetch();
		
		if($queryResult == false){
			$result = "FALSE";
		}
		else{
			$result = "TRUE";
		}
		return($result);
	}
	
	private function save($news,$hash){
		$sourceID = $this->rssSourceManager->getSourceID($news->getshortName());
		if ($sourceID != false){
			$queryHandler = $this->dbConnection->prepare('INSERT INTO news (Id, Title, Resume, Link, Image, PubDate, Source) value (:id,:title,:resume,:link,:image,:pubDate,:source)');
			$params = array(
				'id' => $hash,
			    'title'  =>  $news->getTitle(),
				'resume' => $news->getResume(),
				'link' =>$news->getLink(),
				'image' =>$news->getImage(),
				'pubDate' => DateManager::convertToSql($news->getPubDate()),
				'source' => $sourceID
			);
			$result = $queryHandler->execute($params);
		}
		else{
			$result = false;
		}
		return($result);
	}
}
?>